﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using AEM.Utils;

namespace AEM.Data.BLL.Actions
{
    public static class Log
    {
        static Log()
        {
            AddOperation = doAddOperation;
        }

        private static void doAddOperation(string eventinfo)
        {
            try
            {
                string dir = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "syslogs");
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);
                string filename = Path.Combine(dir, DateTime.Now.ToString("yyyyMMdd") + ".txt");

                string t = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                StreamWriter sw = File.AppendText(filename);
                string msg = string.Format("{0} {1} {2}", Config.userLogin.UserName, t, eventinfo);
                sw.WriteLine(msg);
                sw.Flush();
                sw.Close();

                Config.EventInfoList.Insert(0, Translate(msg));
            }
            catch { }
            if (null != OperationLogChangedEvent)
                OperationLogChangedEvent.Invoke();
        }

        public static void AddOperationCallback(IAsyncResult tag)
        {
            AsyncResult result = (AsyncResult)tag;
            Action<string> del = (Action<string>)result.AsyncDelegate;
            del.EndInvoke(tag);
        }

        /// <summary>
        /// 添加操作日志
        /// 参数一:操作描述
        /// </summary>
        public static Action<string> AddOperation;

        public static Action OperationLogChangedEvent;


        private static DateTime minDate = DateTime.Now;
        public static List<string> LoadEventInfo()
        {
            try
            {
                string dir = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "syslogs");
                string d = (from f in new DirectoryInfo(dir).GetFiles()
                            select f.Name.Replace(f.Extension, "")).Max();

                DateTime dt = DateTime.Now;
                if (!string.IsNullOrEmpty(d))
                {
                    string y = d.Substring(0, 4);
                    string m = d.Substring(4, 2);
                    string dd = d.Substring(6, 2);
                    dt = new DateTime(y.toInt32(), m.toInt32(), dd.toInt32());
                }
                {//init mindate
                    d = (from f in new DirectoryInfo(dir).GetFiles()
                         select f.Name.Replace(f.Extension, "")).Min();
                    if (!string.IsNullOrEmpty(d))
                    {
                        string y = d.Substring(0, 4);
                        string m = d.Substring(4, 2);
                        string dd = d.Substring(6, 2);
                        minDate = new DateTime(y.toInt32(), m.toInt32(), dd.toInt32());
                    }

                }
                var list = ReadLog(dir, dt);
                if (null != list && list.Count > 0)
                {
                    list.Reverse();
                    if (list.Count > 300)
                        list.RemoveRange(300, list.Count - 300);
                    return list;
                }
            }
            catch { }
            return null;
        }

        private static List<string> ReadLog(string dir, DateTime dt)
        {
            List<string> arrText = new List<string>();
            string sLine = "";
            string filename = Path.Combine(dir, dt.ToString("yyyyMMdd") + ".txt");
            if (File.Exists(filename))
            {
                StreamReader objReader = new StreamReader(filename);

                while (sLine != null)
                {
                    sLine = objReader.ReadLine();
                    if (sLine != null)
                        arrText.Add(Translate(sLine));
                }
                objReader.Close();
            }
            if (arrText.Count < 300)
            {
                DateTime next = dt.AddDays(-1);
                if (next < minDate) return arrText;
                List<string> arr = ReadLog(dir, next);
                if (null != arr)
                    arrText.InsertRange(0, arr);
            }

            return arrText;
        }

        private static string Translate(string sLine)
        {
            string[] t = sLine.Split('=');
            string[] msg = t[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string[] son = new string[msg.Length - 1];
            try
            {
                Array.Copy(msg, 1, son, 0, msg.Length - 1);
                for (int i = 0; i < son.Length; i++)
                {
                    if (!son[i].isNumeric()) son[i] = System.Windows.Application.Current.TryFindResource(son[i]) as string;
                }
            }
            catch { }
            t[1] = string.Format(System.Windows.Application.Current.TryFindResource(msg[0]) as string, son);

            return t.Join("");
        }
    }
}
